﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DevExpress.Xpf.Editors;
using System.Threading;
using DevExpress.Xpf.Core;
using GifImageLib;
using System.IO;
using System.Drawing;
using System.Resources;

namespace Cinser.Common.Wpf.Controls
{
    public delegate int ReturnIntHandler();  //返回Object的委托
    public delegate bool ReturnBoolHandler();  //返回Object的委托
    public delegate void NoReturnHandler(); //无返回值无参方法的委托
    public delegate string ReturnStrHandler();
    public delegate double ReturnDoubleHandler();


    public enum ProgImageTypeEm
    {
        None = 0,
        Succeed,
        Warn,
        Error
    }
    public class ProgressListItem
    {
        public ProgImageTypeEm ImageType;
        public string Text;
        public ProgressListItem()
        {
        }
        public ProgressListItem(string txt, ProgImageTypeEm type)
        {
            Text = txt;
            ImageType = type;
        }
    }
    public class ProgressList
    {
        public List<ProgressListItem> list = new List<ProgressListItem>();

        public void Append(string notice, ProgImageTypeEm type)
        {
            ProgressListItem item = new ProgressListItem(notice, type);
            list.Add(item);
        }
        public void Append(ProgressListItem item)
        {
            list.Add(item);

        }

        public void Clear()
        {
            list = new List<ProgressListItem>();
        }


        public int Count
        {
            get
            {
                return list.Count;
            }
        }



        public ProgressListItem this[int i]
        {
            get
            {
                return list[i];
            }
        }
    }
    /// <summary>
    /// Interaction logic for DXWindow1.xaml
    /// </summary>
    public partial class WinProgress : DXWindow
    {
        public string ThemeName = "Office2007Blue";
        public ReturnStrHandler GetProgTitle;
        public ReturnStrHandler GetProgCurOperation;
        public ReturnDoubleHandler GetProgPosition;
        public NoReturnHandler WorkMethod;
        public ReturnBoolHandler WorkMethodBool;
        GifImage imgWait;
        ProgressList listInfo = new ProgressList();

        //ImageSource imgSrcSucceed = new BitmapImage(new Uri("/Cinser.Common.Wpf;component/Images/info.png", UriKind.RelativeOrAbsolute));
        //ImageSource imgSrcWarn = new BitmapImage(new Uri("/Cinser.Common.Wpf;component/Images/warn.png", UriKind.RelativeOrAbsolute));
        //ImageSource imgSrcError = new BitmapImage(new Uri("/Cinser.Common.Wpf;component/Images/error.png", UriKind.RelativeOrAbsolute));

        ImageSource imgSrcSucceed = null;
        ImageSource imgSrcWarn = null;
        ImageSource imgSrcError = null;
        private double progPosition;  //进度，应为小于100的整数
        public double ProgPosition
        {
            get { return progPosition; }
            set { progPosition = value; }
        }

        public int iCurIndex = 0;
        Thread thMain;
        Thread th;

        private bool ExpBtnVisibility = false;
        public bool ExportButtonVisibility
        {
            get { return ExpBtnVisibility; }
            set { ExpBtnVisibility = value; }
        }


        /// <summary>
        /// 初始化进度条窗口类
        /// </summary>
        /// <param name="GetProgTitle">流程标题</param>
        /// <param name="GetProgCurOperation">正在操作</param>
        /// <param name="GetProgPosition">进度条位置</param>
        /// <param name="list">ListBox内容列表</param>
        /// <param name="workMet">操作函数</param>
        public WinProgress(
            ReturnStrHandler GetProgTitle,
            ReturnStrHandler GetProgCurOperation,
            ReturnDoubleHandler GetProgPosition,
            ProgressList list,
            NoReturnHandler workMet)
        {
            InitializeComponent();
            //设置列表项前面的图标
            ResourceManager resourceManager = Cinser.Common.Wpf.Resource.ResourceManager; // Properties.Resources;
            imgSrcSucceed = BitmapToBitmapImage((Bitmap)resourceManager.GetObject("info"));            
            imgSrcWarn = BitmapToBitmapImage((Bitmap)resourceManager.GetObject("warn"));
            imgSrcError = BitmapToBitmapImage((Bitmap)resourceManager.GetObject("error"));
            //设置等待GIF图标
            Bitmap gifSrcWait = (Bitmap)resourceManager.GetObject("Wait");
            MemoryStream ms = new MemoryStream();
            gifSrcWait.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            gif.SetSource(ms);

            this.Resources.FindName("info");
            this.GetProgTitle = GetProgTitle;
            this.GetProgCurOperation = GetProgCurOperation;
            this.GetProgPosition = GetProgPosition;
            this.listInfo = list;
            this.WorkMethod = workMet;
        }
        /// <summary>
        /// 将Bitmap转换成BitmapSource
        /// </summary>
        private static System.Windows.Media.Imaging.BitmapSource BitmapToBitmapImage(Bitmap bitmap)
        {
            if (bitmap == null) return null;
            IntPtr ip = bitmap.GetHbitmap();
            System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                ip, IntPtr.Zero, Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            return bitmapSource;
        }

        //public WinProgress(
        //    ReturnStrHandler GetProgTitle,
        //    ReturnStrHandler GetProgCurOperation,
        //    ReturnDoubleHandler GetProgPosition,
        //    ProgressList list,
        //    ReturnBoolHandler workMet)
        //{
        //    InitializeComponent();

        //    this.GetProgTitle = GetProgTitle;
        //    this.GetProgCurOperation = GetProgCurOperation;
        //    this.GetProgPosition = GetProgPosition;
        //    this.listInfo = list;
        //    this.WorkMethodBool = workMet;
        //}


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (ExpBtnVisibility == false)
            {
                this.btnExport.Visibility = Visibility.Hidden;
            }
            if (!string.IsNullOrEmpty(ThemeName))
            {
                ThemeManager.SetThemeName(this, ThemeName);
            }
            //this.Topmost = true;
            imgWait = this.gif;
            this.progressBar.Value = 0;
            this.ProgPosition = 0;
            thMain = new System.Threading.Thread(new ThreadStart(delegate
            {
                try
                {
                    if (WorkMethod != null)
                    {
                        //让Action委托中这段代码在主线程的执行，控件都是在主线程上创建的，控件的操作只能在主线程里面执行
                        
                        this.Dispatcher.Invoke(new Action(() =>
                        {
                            this.btnExit.IsEnabled = false;
                            this.btnExport.IsEnabled = false;
                        }));
                        WorkMethod();
                        this.Dispatcher.Invoke(new Action(() =>
                        {
                            this.btnExit.IsEnabled = true;
                            this.btnExport.IsEnabled = true;
                            this.gif.Visibility = System.Windows.Visibility.Hidden;
                            this.progPosition = 100;
                            //this.progressBar.EditValue = this.progPosition;
                            this.progressBar.Value = this.progPosition;
                        }));
                    }
                }
                catch(Exception ex)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        ShowMessage.Error("操作异常," + ex.Message);
                    }));
                }

            }));
            thMain.IsBackground = true;
            thMain.Start();
            th = new System.Threading.Thread(RefreshWin);
            th.IsBackground = true;
            th.Start();
        }

        private void RefreshWin()
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                this.listBox.Items.Clear();
                iCurIndex = 0;
            }));
            while (true)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {

                    while (iCurIndex < listInfo.Count)
                    {
                        ListBoxEditItem item = new ListBoxEditItem();
                        item.VerticalAlignment = VerticalAlignment.Center;

                        StackPanel sp = new StackPanel();
                        sp.Orientation = Orientation.Horizontal;

                        TextBlock txt = new TextBlock();
                        txt.VerticalAlignment = VerticalAlignment.Center;
                        txt.Text = " " + listInfo[iCurIndex].Text;


                        System.Windows.Controls.Image img = new System.Windows.Controls.Image();
                        img.Width = 16;
                        img.Height = 16;
                        img.Source = GetImageSource(listInfo[iCurIndex].ImageType);

                        sp.Children.Add(img);
                        sp.Children.Add(txt);
                        item.Content = sp;

                        listBox.Items.Add(item);
                        listBox.SelectedItem = item;
                        listBox.ScrollIntoView(item);

                        iCurIndex++;
                    }


                    if (GetProgPosition != null)
                    {
                        this.progPosition = GetProgPosition();
                        this.progressBar.Value = this.progPosition;
                        if (this.progPosition > 100)
                            this.progPosition = 100;
                        //this.progressBar.Content = this.progPosition.ToString("F2") + "%";
                        lbMsg.Content = this.progPosition.ToString("F2") + "%";
                    }
                    if (GetProgTitle != null && this.txtProgTitle.Text != GetProgTitle())
                    {
                        this.txtProgTitle.Text = GetProgTitle();
                    }
                    if (GetProgCurOperation != null && this.txtProgCurOperation.Text != GetProgCurOperation())
                    {
                        this.txtProgCurOperation.Text = GetProgCurOperation();
                    }
                    if (progPosition == 100 && iCurIndex == this.listInfo.Count)
                    {
                        if (this.sp.Children.Contains(this.imgWait))
                        {
                            this.sp.Children.Remove(imgWait);
                        }
                        //thMain.Abort();
                        //th.Abort();
                        return;
                    }
                    else
                    {
                        if (!this.sp.Children.Contains(this.imgWait))
                        {
                            this.sp.Children.Insert(0, imgWait);
                        }
                    }

                }
                    ));
                Thread.Sleep(10);
            }
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string txtfile = string.Format("{0}\\Cache\\VerifyHistory.txt",
                    System.Environment.CurrentDirectory);

                StreamWriter sw = new StreamWriter(txtfile, false);
                for (int i = 0; i < listBox.Items.Count; i++)
                {
                    //ListBoxEditItem item = ((ListBoxEditItem)listBox.Items[i]).Content;
                    //item.Content
                    //listBox.Items[9].
                    string strLine = ((TextBlock)(((StackPanel)((ListBoxEditItem)listBox.Items[i]).Content).Children[1])).Text;
                    sw.WriteLine(strLine);
                }
                sw.Close();//写入

                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = txtfile; //example:@"D:\者员信息.xls";
                p.Start();
            }
            catch
            {
                ShowMessage.Error("打开历史记录失败!");
            }



        }
        private void btnRedo_Click(object sender, RoutedEventArgs e)
        {
            if (thMain.IsAlive) return;
            thMain = new System.Threading.Thread(new ThreadStart(delegate
            {
                if (WorkMethod != null)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.btnExit.IsEnabled = false;
                        
                        this.btnExport.IsEnabled = false;
                    }));
                    WorkMethod();
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.btnExit.IsEnabled = true;
                        this.btnExport.IsEnabled = true;
                    }));
                }
            }));
            thMain.IsBackground = true;
            thMain.Start();
            th = new System.Threading.Thread(RefreshWin);
            th.IsBackground = true;
            th.Start();
        }
        private void DXWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (thMain.IsAlive)
            {
                ShowMessage.Warnning("操作正在进行中,此时退出会导致数据错误，请稍候...");
                e.Cancel = true;
            }
          //  if (th.IsAlive) th.Abort();
        }

        private ImageSource GetImageSource(ProgImageTypeEm type)
        {
            switch (type)
            {
                case ProgImageTypeEm.Succeed:
                    return imgSrcSucceed;
                // break;
                case ProgImageTypeEm.Warn:
                    return imgSrcWarn;
                // break;
                case ProgImageTypeEm.Error:
                    return imgSrcError;
                // break;
                default:
                    return null;
                // break;
            }
        }
    }
}
